package cn.itcast.nems.listener;

import cn.itcast.nems.common.account.AccountHolder;
import cn.itcast.nems.common.account.AccountInfo;
import cn.itcast.nems.common.tenant.TenantInfo;
import cn.itcast.nems.common.tenant.TenantInfoHolder;
import cn.itcast.nems.employee.dao.condition.EmployeeEvent;
import cn.itcast.nems.employee.dao.entity.Employee;
import cn.itcast.nems.employee.service.EmployeeService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;

/**
 * 员工表（e2_employee）从员工中心自动同步员工入职和离职信息，并增加四个字段：【所属部门】、【状态（在、离职）】、【入职时间】、【离职时间】
 * 从员工中心自动同步人员
 * 1.入职
 * 2.离职
 * 3.转岗
 * Tags： EmployeePostEvent(转岗), EmployeeLeaveEvent(离职), EmployeeDelEvent(删除), EmployeeDisabledEvent(禁用), EmployeeEnableEvent(启用),EmployeeNewEvent(入职)
 */
@Slf4j
@Component
@RocketMQMessageListener(
        topic = "${msas.employee.rocketmq.topic}",
        consumerGroup = "${msas.employee.rocketmq.group-id.EmployeeEvent}",
        nameServer = "${msas.employee.rocketmq.name-server}",
        accessKey = "${msas.employee.rocketmq.access-key}",
        secretKey = "${msas.employee.rocketmq.secret-key}")
public class EmployeeEventQueueListener implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener {
    @Autowired
    private EmployeeService employeeService;

    @Override
    public void onMessage(MessageExt messageExt) {
        if (messageExt == null) {
            return;
        }
        String tag = messageExt.getTags();
        if (!StringUtils.hasText(tag)) {
            return;
        }
        // EmployeeNewEvent(入职),EmployeePostEvent(转岗), EmployeeLeaveEvent(离职)
        if (!tag.equals("EmployeeNewEvent") && !tag.equals("EmployeePostEvent") && !tag.equals("EmployeeLeaveEvent")) {
            return;
        }
        String msg = new String(messageExt.getBody(), StandardCharsets.UTF_8);
        if (!StringUtils.hasText(msg)) {
            return;
        }
        EmployeeEvent employeeEvent = JSON.parseObject(msg, EmployeeEvent.class);
        if (employeeEvent == null) {
            return;
        }
        log.info("从员工中心自动同步人员 {}，{}", tag, JSON.toJSONString(employeeEvent));
        String email = employeeEvent.getEmail();
        if (!StringUtils.hasText(email)) {
            return;
        }
        email = email.replace(" ", "");
        employeeEvent.setEmail(email);
        AccountHolder.setAccountInfo(new AccountInfo(email, employeeEvent.getName(), employeeEvent.getEmployeeNumber(), employeeEvent.getDepartmentName()));
        TenantInfoHolder.setTenantInfo(TenantInfo.DEFAULT_TENANT_INFO);
        // 通过邮箱查询用户
        Employee employee = employeeService.findOneByEmail(email);

        // 入职、转岗
        if (tag.equals("EmployeeNewEvent") || tag.equals("EmployeePostEvent")) {
            if (employee == null) {
                // 通过邮箱查询用户不存在-执行添加用户操作
                this.createdEmployee(employeeEvent);
            } else {
                // 修改操作
                this.updateEmployee(employee.getId(), employeeEvent);
            }
        } else if (tag.equals("EmployeeLeaveEvent")) {
            if (employee != null) {
                // 离职
                employeeService.updateStatus(employee.getId(), 2);
            }
        }
    }


    /**
     * 添加用户
     *
     * @param employeeEvent
     */
    private void createdEmployee(EmployeeEvent employeeEvent) {
        Employee employee = new Employee();
        employee.setDepartmentId(employeeEvent.getDepartmentId());
        employee.setDepartmentName(employeeEvent.getDepartmentName());
        employee.setEmail(employeeEvent.getEmail());
        employee.setName(employeeEvent.getName());
        employee.setJobNumber(employeeEvent.getEmployeeNumber());
        employee.setStatus(1);
        employeeService.created(employee);
    }

    /**
     * 修改用户
     *
     */
    private void updateEmployee(String employeeId, EmployeeEvent employeeEvent) {
        Employee employee = new Employee();
        employee.setId(employeeId);
        employee.setDepartmentId(employeeEvent.getDepartmentId());
        employee.setDepartmentName(employeeEvent.getDepartmentName());
        employee.setEmail(employeeEvent.getEmail());
        employee.setName(employeeEvent.getName());
        employee.setJobNumber(employeeEvent.getEmployeeNumber());
        employee.setStatus(1);
        employeeService.update(employee);
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        defaultMQPushConsumer.setConsumeTimeout(1);
        defaultMQPushConsumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        defaultMQPushConsumer.setMaxReconsumeTimes(3);
        defaultMQPushConsumer.setMessageModel(MessageModel.CLUSTERING);
    }

}